<template>
	<div>
		<el-form :inline="true">
			<el-form-item>
				<el-input
						v-model="searchForm.apply_no"
						placeholder="请输入申请编号"
						clearable
					>
					</el-input>
			</el-form-item>

			<el-form-item>
				<el-input
						v-model="searchForm.device_name"
						placeholder="请输入设备名称"
						clearable
					>
					</el-input>
			</el-form-item>

			<el-form-item>
				<el-select v-model="searchForm.status" placeholder="完成状态">
					<el-option label="全部" :value="''"></el-option>
					<el-option label="待完成" :value="0"></el-option>
					<el-option label="已完成" :value="1"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item>
				<el-button @click="getCompleteList">查询</el-button>
			</el-form-item>

			<el-form-item>
				<el-button @click="resetSearch">重置</el-button>
			</el-form-item>
		</el-form>

		<el-table
				:data="tableData"
				tooltip-effect="dark"
				style="width: 100%"
				border
				stripe>

			<el-table-column
			prop="requestCode"
			label="申请编号">
		</el-table-column>
			<el-table-column
			prop="deviceName"
			label="设备名称"
			show-overflow-tooltip>
			</el-table-column>
			<el-table-column
			prop="deviceCode"
			label="设备编号"
			show-overflow-tooltip>
			</el-table-column>
				<el-table-column
					prop="faultDescription"
					label="故障描述">
				</el-table-column>
				<el-table-column
					prop="repairUserName"
					label="维修人员">
				</el-table-column>
				<el-table-column
			prop="assignTime"
			label="指派时间">
			</el-table-column>
				<el-table-column
					prop="status"
					label="完成状态">
				<template slot-scope="scope">
						<el-tag size="small" v-if="scope.row.status === 2" type="info">待完成</el-tag>
						<el-tag size="small" v-else-if="scope.row.status === 3" type="success">已完成</el-tag>
					</template>
			</el-table-column>
			<el-table-column
			prop="completionTime"
			label="完成时间">
		</el-table-column>
				<el-table-column
			prop="estimatedCost"
			label="预计费用">
				<template slot-scope="scope">
					<span>{{ scope.row.estimatedCost || 0 }} 元</span>
				</template>
			</el-table-column>
				<el-table-column
			prop="actualCost"
			label="实际费用">
				<template slot-scope="scope">
					<span>{{ scope.row.actualCost || 0 }} 元</span>
				</template>
			</el-table-column>
			<el-table-column
					label="操作">
				<template slot-scope="scope">
					<el-button type="text" @click="detail_handle(scope.row.id)" >详情</el-button>
					<el-divider direction="vertical"></el-divider>

					<template v-if="scope.row.status === 2">
						<el-button type="text" @click="complete_task(scope.row.id)" >确认完成</el-button>
					</template>
					<template v-else>
						<el-button type="text" @click="view_complete_info(scope.row.id)" >查看维修结果</el-button>
					</template>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100]"
				:current-page="page_num"
				:page-size="page_size"
				:total="total">
		</el-pagination>

		<!--完成确认对话框-->
		<el-dialog
			title="确认完成维修"
			:visible.sync="complete_dialog_visible"
			width="600px"
			@close="closeDialog_complete">

			<el-form :model="complete_form" :rules="complete_form_rules" ref="complete_form">
				<el-form-item label="维修结果" prop="result" label-width="120px">
					<el-radio-group v-model="complete_form.result">
						<el-radio :label="1">修复成功</el-radio>
						<el-radio :label="2">临时修复</el-radio>
						<el-radio :label="3">无法修复</el-radio>
					</el-radio-group>
			</el-form-item>

			<el-form-item label="完成时间" prop="complete_time" label-width="120px">
						<el-date-picker v-model="complete_form.complete_time" type="datetime" placeholder="选择日期时间"></el-date-picker>
			</el-form-item>

			<el-form-item label="维修说明" prop="complete_note" label-width="120px">
					<el-input v-model.trim="complete_form.complete_note" type="textarea" rows="4"></el-input>
			</el-form-item>

			<el-form-item label="更换零件" label-width="120px">
						<el-input v-model.trim="complete_form.replace_parts" type="textarea" rows="3"></el-input>
				</el-form-item>
				<el-form-item label="预计费用" label-width="120px">
						<el-input v-model.number="complete_form.estimatedCost" type="number" placeholder="请输入预计费用"></el-input>
				</el-form-item>
				<el-form-item label="实际费用" label-width="120px">
						<el-input v-model.number="complete_form.actualCost" type="number" placeholder="请输入实际费用"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="complete_dialog_visible = false">取 消</el-button>
				<el-button type="primary" @click="submit_complete_form">确 定</el-button>
			</div>
		</el-dialog>

		<!--详情对话框-->
		<el-dialog
			title="申请详情"
			:visible.sync="detail_visible"
			width="600px"
			@close="closeDialog_detail">

			<el-form :model="detail_form" label-width="120px">
				<el-form-item label="申请编号">
					<span>{{ detail_form.requestCode }}</span>
			</el-form-item>
			<el-form-item label="设备名称">
					<span>{{ detail_form.deviceName || '未知设备' }}</span>
			</el-form-item>
			<el-form-item label="设备编号">
				<span>{{ detail_form.deviceCode || '-' }}</span>
			</el-form-item>
			<el-form-item label="故障描述">
				<span>{{ detail_form.faultDescription || '-' }}</span>
			</el-form-item>
			<el-form-item label="维修人员">
				<span>{{ detail_form.repairUserName || '未分配' }}</span>
			</el-form-item>
			<el-form-item label="指派时间">
				<span>{{ detail_form.assignTime || '-' }}</span>
			</el-form-item>
			<el-form-item label="完成状态">
				<el-tag size="small" v-if="detail_form.status === 2" type="info">待完成</el-tag>
				<el-tag size="small" v-else-if="detail_form.status === 3" type="success">已完成</el-tag>
			</el-form-item>
			<el-form-item label="完成时间" v-if="detail_form.completionTime">
					<span>{{ detail_form.completionTime }}</span>
			</el-form-item>
			<el-form-item label="预计费用">
				<span>{{ detail_form.estimatedCost || 0 }} 元</span>
			</el-form-item>
			<el-form-item label="实际费用">
				<span>{{ detail_form.actualCost || 0 }} 元</span>
			</el-form-item>
		</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="detail_visible = false">关闭</el-button>
			</div>
		</el-dialog>

		<!--维修结果对话框-->
		<el-dialog
			title="维修结果"
			:visible.sync="complete_info_visible"
			width="600px"
			@close="closeDialog_complete_info">

			<el-form :model="complete_info_form" label-width="120px">
				<el-form-item label="维修结果">
					<el-tag size="small" v-if="complete_info_form.result === 1" type="success">修复成功</el-tag>
				<el-tag size="small" v-else-if="complete_info_form.result === 2" type="warning">临时修复</el-tag>
				<el-tag size="small" v-else-if="complete_info_form.result === 3" type="danger">无法修复</el-tag>
			</el-form-item>
			<el-form-item label="完成时间">
				<span>{{ complete_info_form.completionTime }}</span>
			</el-form-item>
			<el-form-item label="维修说明">
				<span>{{ complete_info_form.repairRemarks }}</span>
			</el-form-item>
			<el-form-item label="更换零件">
				<span>{{ complete_info_form.replaceParts }}</span>
			</el-form-item>
			<el-form-item label="预计费用">
				<span>{{ complete_info_form.estimatedCost || 0 }} 元</span>
			</el-form-item>
			<el-form-item label="实际费用">
				<span>{{ complete_info_form.actualCost || 0 }} 元</span>
			</el-form-item>
			<el-form-item label="设备名称">
				<span>{{ complete_info_form.deviceName || '未知设备' }}</span>
			</el-form-item>
			<el-form-item label="设备编号">
				<span>{{ complete_info_form.deviceCode || '-' }}</span>
			</el-form-item>
			<el-form-item label="维修人员">
				<span>{{ complete_info_form.repairUserName || '未分配' }}</span>
			</el-form-item>
			<el-form-item label="指派时间">
				<span>{{ complete_info_form.assignTime || '-' }}</span>
			</el-form-item>
			<el-form-item label="优先级">
				<span>{{ complete_info_form.priority === 1 ? '高' : (complete_info_form.priority === 2 ? '中' : '低') }}</span>
			</el-form-item>
		</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="complete_info_visible = false">关闭</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import repairApi from '@/api/repair-request.js'
import deviceApi from '@/api/device.js'
import sysUserApi from '@/api/sys-user.js'
	export default {
			name: "MaintenanceComplete",
			data() {
					return {
						searchForm: {
							apply_no: '',
							device_name: '',
							status: ''
						},
				total: 0,
				page_size: 10,
			page_num: 1,

						complete_dialog_visible: false,
				detail_visible: false,
				complete_info_visible: false,
				// 设备信息映射
				deviceMap: {},
				// 用户信息映射
				userMap: {},
				// 缓存已查询的信息，避免重复请求
				complete_form: {
						id: '',
						result: 1,
						complete_time: new Date(),
						complete_note: '',
						replace_parts: '',
						actualCost: 0,
						estimatedCost: 0
				},
				detail_form: {},
				complete_info_form: {},

				tableData: [],

				complete_form_rules: {
						result: [
							{required: true, message: '请选择维修结果', trigger: 'blur'}
						],
						complete_time: [
							{required: true, message: '请选择完成时间', trigger: 'blur'}
						],
						complete_note: [
							{required: true, message: '请填写维修说明', trigger: 'blur'}
						]
				}
			}
		},
		created() {
				// 初始化时获取设备列表用于映射
				this.getDeviceList()
				this.getCompleteList()
			},
		methods: {
			// 根据ID获取用户信息
			getUserInfo(userId) {
				if (!userId) return
				sysUserApi.detail(userId).then(res => {
					if (res && res.data) {
						this.$set(this.userMap, userId, res.data.username || '未知用户')
						// 更新表格数据中的用户信息
						this.updateTableUserInfo(userId)
					}
				}).catch(error => {
					console.error(`获取用户ID ${userId} 信息失败:`, error)
				})
			},
			// 更新表格中的用户信息
			updateTableUserInfo(userId) {
				const userName = this.userMap[userId]
				if (userName && this.tableData.length > 0) {
					this.tableData = this.tableData.map(item => {
						if ((item.repairUserId || item.repair_user_id) === userId) {
							return {
								...item,
								repairUserName: userName
							}
						}
						return item
					})
				}
				// 更新详情表单中的用户信息
				if (this.detail_visible && this.detail_form && ((this.detail_form.repairUserId || this.detail_form.repair_user_id) === userId)) {
					this.$set(this.detail_form, 'repairUserName', userName)
				}
				// 更新维修结果表单中的用户信息
				if (this.complete_info_visible && this.complete_info_form && ((this.complete_info_form.repairUserId || this.complete_info_form.repair_user_id) === userId)) {
					this.$set(this.complete_info_form, 'repairUserName', userName)
				}
			},
			closeDialog_detail() {
				this.detail_visible = false
			},
			closeDialog_complete_info() {
				this.complete_info_visible = false
			},
			closeDialog_complete() {
				this.complete_dialog_visible = false
			},
			// 获取设备列表
			getDeviceList() {
				deviceApi.list().then(res => {
					let deviceData = []
					// 处理不同的数据返回格式
					if (Array.isArray(res)) {
						deviceData = res
					} else if (res && res.data) {
						if (Array.isArray(res.data)) {
							deviceData = res.data
						} else if (Array.isArray(res.data.records)) {
							deviceData = res.data.records
						}
					}
					// 构建设备映射表
					deviceData.forEach(device => {
						this.$set(this.deviceMap, device.id, {
							deviceName: device.deviceName || device.name || '未知设备',
							deviceCode: device.deviceCode || device.code || ''
						})
					})
				}).catch(error => {
					console.error('获取设备列表失败:', error)
				})
			},
			// 根据ID获取单个设备信息
			getDeviceInfo(deviceId) {
				if (!deviceId) return
				deviceApi.detail(deviceId).then(res => {
					if (res && res.data) {
						this.$set(this.deviceMap, deviceId, {
							deviceName: res.data.deviceName || res.data.name || '未知设备',
							deviceCode: res.data.deviceCode || res.data.code || ''
						})
						// 更新表格数据中的设备信息
						this.updateTableDeviceInfo(deviceId)
					}
				}).catch(error => {
					console.error(`获取设备ID ${deviceId} 信息失败:`, error)
				})
			},
			// 更新表格中的设备信息
			updateTableDeviceInfo(deviceId) {
				const deviceInfo = this.deviceMap[deviceId]
				if (deviceInfo && this.tableData.length > 0) {
					this.tableData = this.tableData.map(item => {
						if ((item.deviceId || item.device_id) === deviceId) {
							return {
								...item,
								deviceName: deviceInfo.deviceName,
								deviceCode: deviceInfo.deviceCode
							}
						}
						return item
					})
				}
				// 更新详情表单中的设备信息
				if (this.detail_visible && this.detail_form && ((this.detail_form.deviceId || this.detail_form.device_id) === deviceId)) {
					this.$set(this.detail_form, 'deviceName', deviceInfo.deviceName)
					this.$set(this.detail_form, 'deviceCode', deviceInfo.deviceCode)
				}
			},
			handleSizeChange(val) {
				this.page_size = val
				this.getCompleteList()
			},
			handleCurrentChange(val) {
				this.page_num = val
				this.getCompleteList()
			},
			resetSearch() {
				this.searchForm = {
					apply_no: '',
					device_name: '',
					status: ''
				}
				this.getCompleteList()
			},

			getCompleteList() {
			repairApi.list({
					requestCode: this.searchForm.apply_no,
					deviceName: this.searchForm.device_name,
					// 映射完成状态到status字段
					status: this.searchForm.status === '0' ? 2 : (this.searchForm.status === '1' ? 3 : ''),
					page_num: this.page_num,
			page_size: this.page_size
				}).then(res => {
					if (res && res.data) {
						// 处理可能是分页数据或直接数组的情况
						const rawData = Array.isArray(res.data) ? res.data : (res.data.records || [])
						// 处理数据，确保关联字段正确显示
						this.tableData = rawData.map(item => {
							const deviceId = item.deviceId || item.device_id
							// 获取设备信息
							const deviceInfo = this.deviceMap[deviceId] || {}
							return {
								...item,
								// 根据deviceId确保设备信息正确显示
								deviceName: item.deviceName || deviceInfo.deviceName || '未知设备',
								deviceCode: item.deviceCode || deviceInfo.deviceCode || '',
								// 根据repairUserId确保维修人员信息正确显示
								repairUserName: item.repairUserName || '未分配',
								// 确保指派时间正确显示
								assignTime: item.assignTime || item.requestTime
							}
						})
						// 确保所有设备ID都已获取设备信息
				rawData.forEach(item => {
					const deviceId = item.deviceId || item.device_id
					if (deviceId && !this.deviceMap[deviceId]) {
						this.getDeviceInfo(deviceId)
					}
					// 确保所有维修人员ID都已获取用户信息
					const repairUserId = item.repairUserId || item.repair_user_id
					if (repairUserId && !this.userMap[repairUserId]) {
						this.getUserInfo(repairUserId)
					}
				})
						this.page_size = res.data.page_size || this.page_size
						this.page_num = res.data.page_num || this.page_num
						this.total = res.data.total || (Array.isArray(res.data) ? res.data.length : 0)
					} else {
						this.tableData = []
						this.total = 0
					}
				}).catch(error => {
					this.tableData = []
					this.total = 0
					this.$message.error('获取维修完成列表失败：' + (error.message || '未知错误'))
					console.error('获取维修完成列表失败:', error)
				})
			},

			complete_task(id) {
				// 根据id初始化完成表单
				this.complete_form = {
							id: id,
							result: 1,
							complete_time: new Date(),
							complete_note: '',
							replace_parts: '',
							actualCost: 0,
							estimatedCost: 0
						}
				this.complete_dialog_visible = true
			},

				submit_complete_form() {
				this.$refs['complete_form'].validate((valid) => {
					if (valid) {
						// 添加时间戳并设置完成状态，与数据库status字段对应（3:已完成）
						const formData = {
							requestId: this.complete_form.id,
							repairRemarks: this.complete_form.complete_note,
							result: this.complete_form.result,
							completionTime: this.complete_form.complete_time,
							replaceParts: this.complete_form.replace_parts,
							status: 3, // 明确设置为已完成状态
							actualCost: this.complete_form.actualCost,
							estimatedCost: this.complete_form.estimatedCost
						}
						repairApi.complete(formData).then(res => {
						this.$message({
							showClose: true,
							message: '维修完成确认成功',
							type: 'success',
							onClose: () => {
								// 代码移到下一行
							}
						});
						this.getCompleteList()
						this.complete_dialog_visible = false
					}).catch(error => {
						this.$message.error('维修完成确认失败：' + (error.message || '未知错误'))
						console.error('维修完成确认失败:', error)
					})
					} else {
						return false;
					}
				});
			},

			detail_handle(id) {
				// 根据id查询详情，确保请求参数正确
				this.detail_form = {}
				this.detail_visible = true
				// 调用详情接口
				repairApi.detail(id).then(res => {
					// 确保字段名称匹配并处理关联数据
					if (res && res.data) {
						// 处理详情数据，确保关联字段正确显示
						this.detail_form = {
							...res.data,
							// 根据deviceId确保设备信息正确显示
							deviceName: res.data.deviceName || '未知设备',
							deviceCode: res.data.deviceCode || '',
							// 根据repairUserId确保维修人员信息正确显示
							repairUserName: res.data.repairUserName || '未分配',
							// 确保指派时间正确显示
							assignTime: res.data.assignTime || res.data.requestTime
						}
							
						// 格式化日期时间显示
						if (this.detail_form.created) {
							this.detail_form.created = this.$moment(this.detail_form.created).format('YYYY-MM-DD HH:mm:ss')
						}
						if (this.detail_form.completionTime) {
							this.detail_form.completionTime = this.$moment(this.detail_form.completionTime).format('YYYY-MM-DD HH:mm:ss')
						}
						// 获取设备信息
					const deviceId = this.detail_form.deviceId || this.detail_form.device_id
					if (deviceId) {
						const deviceInfo = this.deviceMap[deviceId] || {}
						// 更新设备信息
						if (deviceInfo.deviceName) {
							this.detail_form.deviceName = deviceInfo.deviceName
						}
						if (deviceInfo.deviceCode) {
							this.detail_form.deviceCode = deviceInfo.deviceCode
						}
						// 如果设备信息未加载，异步获取
						if (!this.deviceMap[deviceId]) {
							this.getDeviceInfo(deviceId)
						}
					}
					// 获取维修人员信息
					const repairUserId = this.detail_form.repairUserId || this.detail_form.repair_user_id
					if (repairUserId) {
						const userName = this.userMap[repairUserId]
						// 更新用户信息
						if (userName) {
							this.detail_form.repairUserName = userName
						}
						// 如果用户信息未加载，异步获取
						if (!this.userMap[repairUserId]) {
							this.getUserInfo(repairUserId)
						}
					}
					} else {
						this.$message.error('获取数据失败：未找到相关信息')
					}
				}).catch(error => {
					this.$message.error('获取维修申请详情失败：' + (error.message || '未知错误'))
					console.error('获取维修申请详情失败:', error)
				})
			},

				view_complete_info(id) {
				// 根据id查询维修结果
				this.complete_info_form = {}
				this.complete_info_visible = true
				// 调用查询维修结果接口
				repairApi.detail(id).then(res => {
					// 确保字段名称匹配并处理关联数据
					if (res && res.data) {
						// 处理维修结果数据，确保关联字段正确显示
						this.complete_info_form = {
							...res.data,
							// 根据deviceId确保设备信息正确显示
							deviceName: res.data.deviceName || '未知设备',
							deviceCode: res.data.deviceCode || '',
							// 根据repairUserId确保维修人员信息正确显示
							repairUserName: res.data.repairUserName || '未分配',
							// 确保指派时间正确显示
							assignTime: res.data.assignTime || res.data.requestTime
						}
						
						// 获取设备信息
						const deviceId = this.complete_info_form.deviceId || this.complete_info_form.device_id
						if (deviceId) {
							const deviceInfo = this.deviceMap[deviceId] || {}
							// 更新设备信息
							if (deviceInfo.deviceName) {
								this.complete_info_form.deviceName = deviceInfo.deviceName
							}
							if (deviceInfo.deviceCode) {
								this.complete_info_form.deviceCode = deviceInfo.deviceCode
							}
							// 如果设备信息未加载，异步获取
							if (!this.deviceMap[deviceId]) {
								this.getDeviceInfo(deviceId)
							}
						}
						// 获取维修人员信息
						const repairUserId = this.complete_info_form.repairUserId || this.complete_info_form.repair_user_id
						if (repairUserId) {
							const userName = this.userMap[repairUserId]
							// 更新用户信息
							if (userName) {
								this.complete_info_form.repairUserName = userName
							}
							// 如果用户信息未加载，异步获取
							if (!this.userMap[repairUserId]) {
								this.getUserInfo(repairUserId)
							}
						}
					} else {
						this.$message.error('获取数据失败：未找到相关信息')
					}
				}).catch(error => {
					this.$message.error('获取维修结果详情失败：' + (error.message || '未知错误'))
					console.error('获取维修结果详情失败:', error)
				})
			}
		}
	}
</script>

<style scoped>
	.el-pagination {
		float: right;
		margin-top: 22px;
	}
</style>